<template>
  <section class='f-pay'>
    <section class="f-pay-box">
      <div class="g-flex-ct" style="padding: 15px;">
        <img style="width:72px;height:72px;border-radius: 5px;" :src="goodsInfo.headImg" alt="">
        <div class="f-ml-10 f-mt-05">
          <p style="font-size: 16px;color: #000000;">{{orderInfo.goodsName}}</p>
          <p class="f-mt-15" style="color: #FF4628;">
            <span style="font-weight: bold;font-size: 20px;">{{goodsInfo.monthRent/100}}</span>
            <span style="font-size: 12px"> 元/月</span>
          </p>
        </div>
      </div>
      <van-cell-group class="f-mt-10" :border="false">
        <van-cell title="所选号码">
          <template #value>
            <p style="font-size: 14px;color: #000000;">{{orderInfo.goodsPhone}}</p>
          </template>
        </van-cell>
        <van-cell title="预存金额">
          <template #value>
            <p style="font-size: 14px;color: #000000;">¥{{orderInfo.prestoreShow}}</p>
          </template>
        </van-cell>
        <van-cell title="应付金额">
          <template #value>
            <p style="font-size: 14px;color: #FF4628;">¥{{orderInfo.prestorePay}}</p>
          </template>
        </van-cell>
      </van-cell-group>
    </section>

    <van-cell class="f-mt-15" title="支付方式 " is-link readonly @click="off.popup = true">
      <template #value>
        <p style="font-size: 14px;">{{payType[formData.payType]}}</p>
      </template>
    </van-cell>

    <van-popup v-model:show="off.popup" closeable position="bottom" close-icon-position="top-left">
      <p class="f-popup-title">选择支付方式</p>
      <van-radio-group v-model="formData.payType" direction="horizontal" style="padding:22px" @change="off.popup = false">
        <van-radio v-if="isApp || !isWeixin" :name="3" label-position="left" class="f-flex-between" style="width:100%">
          <div class="g-flex-ct">
            <img style="width:30px;height:30px" src="@/assets/icons/withdraw_icon_zfb.png" alt="">
            <p class="f-ml-10" style="font-size: 14px;color: #000000;">支付宝</p>
          </div>
        </van-radio>
        <van-radio v-if="isApp || isWeixin" :name="1" label-position="left" class="f-flex-between f-mt-30" style="width:100%">
          <div class="g-flex-ct">
            <img style="width:30px;height:30px" src="@/assets/icons/withdraw_icon_wx.png" alt="">
            <p class="f-ml-10" style="font-size: 14px;color: #000000;">微信</p>
          </div>
        </van-radio>
        <!-- <van-radio :name="4" label-position="left" class="f-flex-between f-mt-30" style="width:100%">
          <div class="g-flex-ct">
            <img style="height:30px;width:30px" src="@/assets/icons/me_icon_yhk_gray.png" alt="">
            <p class="f-ml-10" style="font-size: 14px;color: #000000;">银行卡</p>
          </div>
        </van-radio> -->
      </van-radio-group>
    </van-popup>

    <van-action-bar>
      <div style="font-size: 20px;color: #FD5356;padding:0 100px 0 13px">¥{{orderInfo.prestorePay}}</div>
      <van-action-bar-button type="danger" color="#488BFE" text="去支付" @click="onSubmit()" />
    </van-action-bar>
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import api from '../api'
import JsBridge from '@/utils/JsBridge.js'
import { errorDeal, successDeal } from '@/utils/utils';
import { showLoadingToast, showToast } from 'vant';

export default {
  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const state = reactive({
      off: {
        popup: false
      },
      orderInfo: {},
      goodsInfo: {},

      formData: {
        payType: 1
      },

      payType: {
        "1": '微信支付',
        "3": '支付宝支付',
        "4": '银行卡支付',
      },

      isApp: computed(() => {
        return store.state.isApp
      }),
      isWeixin: computed(() => {
        var ua = navigator.userAgent.toLowerCase();
        var isWeixin = ua.indexOf('micromessenger') != -1;
        if (isWeixin) {
          return true;
        } else {
          return false;
        }
      }),
    })

    onMounted(() => {
      store.commit("setNavBar", {
        title: '去支付',
        show: true,
        left: true,
        leftType: 'back',
        right: false,
        rightType: 'search',
        bg: ''
      });

      state.formData.payType = state.isWeixin ? 1 : 3

      getOrderDetail()
    })

    const getOrderDetail = () => {
      let json = {
        sysOrderId: route.query.sysOrderId
      }

      api.orderQryDetail(json).then(res => {
        state.orderInfo = res.data
        getGoodsDetail(res.data.goodsId)
      })
    }

    const getGoodsDetail = (goodsId) => {
      let json = {
        goodsId
      }
      api.goodsDetail(json).then(res => {
        state.goodsInfo = res.data
      })
    }

    const onSubmit = () => {
      const { payType } = state.formData
      const realPayType = state.isApp ? payType : (payType == 1 ? 6 : 9)

      let newPage = null
      if (realPayType == 9) {
        newPage = window.open('', '_blank')
      }
      let returnUrl = window.location.origin + window.location.pathname + `#/order`
      let json = {
        "openId": "",
        "payType": realPayType,
        "returnUrl": returnUrl,
        "sysOrderId": route.query.sysOrderId
      }
      api.goodsPay(json).then(res => {
        if (res.code == '200') {
          switch (realPayType) {
            case 1:
              // 微信app支付
              wxAppTopay(res.data)
              break
            case 3:
              // 支付宝APP支付
              aliAppTopay(res.data?.payQRCode)
              break
            case 6:
              // 微信JSAPI支付
              wxTopay(res.data)
              break
            case 9:
              // 支付宝网页支付
              newPage.document.write(res.data?.payQRCode)
              break
          }
        } else {
          newPage && newPage.close()
          showToast(res.msg)
          setTimeout(() => {
            toOrderPage()
          }, 500);
        }
      }).catch(err => {
        newPage && newPage.close()
        console.log(err)
        showToast(err.msg)
        setTimeout(() => {
          toOrderPage()
        }, 500)
      })
    }

    function toOrderPage() {
      router.replace({
        path: '/order',
      })
    }

    function wxAppTopay(data) {
      JsBridge.callHandler('wxPay', data, (res1) => {
        try {
          let data = JSON.parse(res1)
          const { success } = data
          showToast(success ? '支付成功' : '支付失败')
        } catch {
          showToast('支付失败')
        }
        setTimeout(() => {
          toOrderPage()
        }, 500)
      })
    }

    function aliAppTopay(payQRCode) {
      JsBridge.callHandler('alipay', payQRCode, (res1) => {
        try {
          let data = JSON.parse(res1)
          if (data.alipay_trade_app_pay_response.code == 10000) {
            successDeal('支付成功')
          } else {
            errorDeal('支付失败')
          }
        } catch {
          errorDeal('支付失败')
        }
        setTimeout(() => {
          toOrderPage()
        }, 500)
      })
    }

    function wxTopay(wxPayForm) {
      WeixinJSBridge.invoke('getBrandWCPayRequest', {
        "appId": wxPayForm.appid,
        "timeStamp": wxPayForm.timestamp,
        "nonceStr": wxPayForm.noncestr,
        "package": wxPayForm.packageStr,
        "signType": wxPayForm.signType,
        "paySign": wxPayForm.sign,
      },
        function (res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            showToast("支付成功")
          } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
            showToast("取消支付")
          } else {
            //支付失败
            showToast(res.err_msg)
          }
          setTimeout(() => {
            toOrderPage()
          }, 500)
        })
    }

    return {
      ...toRefs(state),
      onSubmit
    }
  }
}
</script>
<style lang='scss' scoped>
.f-pay {
  .f-pay-box {
    background: #fff;
  }
}
</style>